package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseConfirmDialogFragment;
import com.isunland.managesystem.base.BaseMonthTimeDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.base.BaseYMDTimeDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.DynamicConfigLab;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.NumberOriginal;
import com.isunland.managesystem.entity.ProductLedgerOriginal;
import com.isunland.managesystem.entity.ProductSalesOriginal;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import org.json.JSONException;

/**
 * 对象功能:  产品开发费用详情
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2016/6/15 11:13
 */
public class ProductDevelopDetailFragment extends Fragment implements View.OnClickListener {
  protected static final String EXTRA_CONTENT =
      "com.isunland.managesystem.ui.ProductDevelopDetailFragment.EXTRA_CONTENT";
  private static final int DATE = 1;
  private static final int CUSTOMER = 2;
  private static final int PRODUCT = 3;
  private static final int REALDTAE = 4;
  private static final int DELETE = 5;
  private static final int IFREAL = 6;
  private static final int SALES_MAN = 7;
  private static final int SAVE_SUBMIT = 8;
  private static final int SAVE = 9;

  protected static final int ADD = 1;// 添加
  protected static final int EDIT = 2;// 修改
  protected static final int WAIT_CHECK = 3;// 审核中
  protected static final int CHECK_PASS = 4;// 已审核

  private ProductSalesOriginal.ProductSalesContent content;
  private TextView tvMonth;
  private ImageView ibMonth;
  private EditText etMarketName;
  private TextView tvCustomer;
  private ImageView ibCustomer;
  private TextView tvProductType;
  private ImageView ibProductType;
  private TextView tvProductName;

  private EditText etUnitPrice;//单价
  private EditText etPlanMoney;//进货金额
  private TextView tvIfReal;//是否实销
  private ImageView ibIfReal;//是否实销
  private EditText etEstimateSales;//进货数量
  private EditText etActualSales;//实销数量
  private EditText etRealMoney;//实销金额
  private TextView tvMargin;//库存数

  private EditText etActivityCost;//业务活动费
  private EditText etIncreaseCost;//业务增长费
  private EditText etDevelopCost;//开发费
  private TextView tvMonthDiff;//业务增长费比
  private EditText etCmments;//特殊说明

  private TextView tvDataStatus;
  private TextView tvStaffName;//登记人
  private TextView tvSalesman;
  private ImageView ibSalesman;
  private TextView tvRegisterTime;

  private String customerName = "";
  private String customerId = "";
  private String productName = "";
  private String productId = "";
  private String id = "";//记录id
  private String dataStatus = "";//数据状态
  private String ifRealDateCode = "F";//是否实销
  private String saleManName = "";//业务员nme
  private String saleManId = "";//业务员id
  private String ifRealDateName = "是";//是否实销
  private String mProductKindId;//产品类型id
  protected int mMenuType;//菜单
  private BaseVolleyActivity mActivity;
  private CurrentUser mUser;
  private String monthDiffString;

  @Override public void onCreate(Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    BaseVolleyActivity activity = (BaseVolleyActivity) getActivity();
    ActionBar actionBar;
    if (activity != null) {
      actionBar = activity.getSupportActionBar();
      if (actionBar != null) {
        if (NavUtils.getParentActivityName(activity) != null) {
          actionBar.setDisplayHomeAsUpEnabled(true);
        }
        actionBar.setTitle(R.string.productDevelop);
      }
    }
    content =
        (ProductSalesOriginal.ProductSalesContent) getArguments().getSerializable(EXTRA_CONTENT);
    mActivity = (BaseVolleyActivity) getActivity();
    mUser = CurrentUser.newInstance(getActivity());

    super.onCreate(savedInstanceState);
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_productdevelop_detail, container, false);
    findView(v);
    //动态配置列   ---隐藏和显示，title
    DynamicConfigLab.newInstance(mActivity, getString(R.string.module_developExpenseEecord))
        .autoConfigTitle(v);
    DynamicConfigLab.newInstance(mActivity, getString(R.string.module_developExpenseEecord))
        .autoConfigVisiblity(v);
    initData();
    return v;
  }

  private void findView(View v) {
    tvMonth = (TextView) v.findViewById(R.id.tv_month);
    ibMonth = (ImageView) v.findViewById(R.id.ib_month);
    etMarketName = (EditText) v.findViewById(R.id.et_marketName);
    tvCustomer = (TextView) v.findViewById(R.id.tv_customer);
    ibCustomer = (ImageView) v.findViewById(R.id.ib_customer);
    tvProductType = (TextView) v.findViewById(R.id.tv_productType);
    ibProductType = (ImageView) v.findViewById(R.id.ib_productType);
    tvProductName = (TextView) v.findViewById(R.id.tv_product_name);
    etEstimateSales = (EditText) v.findViewById(R.id.et_estimateSales);
    etActualSales = (EditText) v.findViewById(R.id.et_actualSales);
    tvMargin = (TextView) v.findViewById(R.id.tv_margin);
    tvDataStatus = (TextView) v.findViewById(R.id.tv_titleRight);
    tvStaffName = (TextView) v.findViewById(R.id.tv_staffName);
    tvSalesman = (TextView) v.findViewById(R.id.tv_salesman);
    ibSalesman = (ImageView) v.findViewById(R.id.ib_salesMan);//业务员
    tvRegisterTime = (TextView) v.findViewById(R.id.tv_registerTime);

    etUnitPrice = (EditText) v.findViewById(R.id.et_unitPrice);//单价

    etPlanMoney = (EditText) v.findViewById(R.id.et_planMoney);//进货金额
    tvIfReal = (TextView) v.findViewById(R.id.tv_ifReal);//是否实销
    ibIfReal = (ImageView) v.findViewById(R.id.ib_ifReal);
    etRealMoney = (EditText) v.findViewById(R.id.et_realMoney);//实销费用

    etActivityCost = (EditText) v.findViewById(R.id.et_activity_cost);//活动费
    etIncreaseCost = (EditText) v.findViewById(R.id.et_increase_cost);//增长费
    etDevelopCost = (EditText) v.findViewById(R.id.et_develop_cost);//开发费
    tvMonthDiff = (TextView) v.findViewById(R.id.tv_month_diff);//增长比
    etCmments = (EditText) v.findViewById(R.id.et_comments);//备注

    ibMonth.setOnClickListener(ProductDevelopDetailFragment.this);
    ibCustomer.setOnClickListener(ProductDevelopDetailFragment.this);
    ibProductType.setOnClickListener(ProductDevelopDetailFragment.this);
    ibIfReal.setOnClickListener(ProductDevelopDetailFragment.this);
    ibSalesman.setOnClickListener(ProductDevelopDetailFragment.this);
    //监听文字改变
    /** 库存数= 实销数量-进货数量 */
    etEstimateSales.addTextChangedListener(textWatcher());
    etActualSales.addTextChangedListener(textWatcher());

    /** 业务增长费比=业务增长费/实销金额（是否实销为“是”）  或   进货金额（是否实销为“否”）  */
    etIncreaseCost.addTextChangedListener(textWatcher());
    etPlanMoney.addTextChangedListener(textWatcher());
    etRealMoney.addTextChangedListener(textWatcher());
    tvIfReal.addTextChangedListener(textWatcher());
  }

  private void initData() {
    if (content == null) {
      // 添加
      mMenuType = ADD;
      dataStatus = "new";
      ifRealDateCode = "T";
      ifRealDateName = "是";
      saleManName = mUser.getRealName();
      saleManId = mUser.getJobNumber();
      id = UUID.randomUUID().toString();
    } else {
      id = content.getId();
      ifRealDateCode = content.getIfRealData();

      if ("T".equals(ifRealDateCode)) {
        ifRealDateName = "是";
      } else if ("F".equals(ifRealDateCode)) {
        ifRealDateName = "否";
      }
      // 其他
      String dataStattus = content.getDataStatus();
      if (dataStattus.equals("已提交")) {
        mMenuType = WAIT_CHECK;
      }
      if (dataStattus.equals("退回修改") || dataStattus.equals("草稿")) {
        mMenuType = EDIT;
        if (dataStattus.equals("退回修改")) {
          dataStatus = "newback";
        }
        if (dataStattus.equals("草稿")) {
          dataStatus = "new";
        }
      }
    }

    /**初始化控件*/

    if (content != null) {
      productName = content.getProduct();
      customerName = content.getCustomer();

      customerId = content.getCustomerId();
      productId = content.getProductId();
      mProductKindId = content.getProductKindId();

      saleManName = content.getSalesManName();
      saleManId = content.getSalesManId();
      if (!TextUtils.isEmpty(content.getInMonth())) {
        tvMonth.setText(content.getInMonth());//时间
      } else {
        tvMonth.setText(" ");//时间
      }

      etMarketName.setText(content.getMarketend());
      if (!TextUtils.isEmpty(content.getCustomer())) {
        tvCustomer.setText(content.getCustomer());
      } else {
        tvCustomer.setText(" ");
      }
      if (!TextUtils.isEmpty(content.getProductKind())) {
        tvProductType.setText(content.getProductKind());
      } else {
        tvProductType.setText(" ");
      }
      tvProductName.setText(content.getProduct());
      etEstimateSales.setText(content.getPlanData());
      etActualSales.setText(content.getRealData());
      tvMargin.setText(content.getDifferent());
      tvDataStatus.setText(content.getDataStatus());
      tvStaffName.setText(content.getRegStaffName());
      tvSalesman.setText(content.getSalesManName());
      tvRegisterTime.setText(content.getRegDate());
      //新增

      etUnitPrice.setText(content.getReceiptPrice());
      etPlanMoney.setText(content.getPlanMoney());
      if ("T".equals(ifRealDateCode)) {
        tvIfReal.setText(R.string.isTrue);
      } else if ("F".equals(ifRealDateCode)) {
        tvIfReal.setText(R.string.isFalse);
      }
      etRealMoney.setText(content.getRealMoney());
      etActivityCost.setText(content.getActivityCost());
      etIncreaseCost.setText(content.getIncreaseCost());

      etDevelopCost.setText(content.getDevelopCost());
      tvMonthDiff.setText(content.getMonthDiff());
      etCmments.setText(content.getComments());

      if ("已提交".equals(content.getDataStatus())) {
        ibMonth.setVisibility(View.GONE);
        ibCustomer.setVisibility(View.GONE);
        ibProductType.setVisibility(View.GONE);
        ibIfReal.setVisibility(View.GONE);
        ibSalesman.setVisibility(View.GONE);

        etMarketName.setEnabled(false);
        etEstimateSales.setEnabled(false);
        etActualSales.setEnabled(false);
        etUnitPrice.setEnabled(false);
        etPlanMoney.setEnabled(false);
        etEstimateSales.setEnabled(false);
        etActualSales.setEnabled(false);
        etRealMoney.setEnabled(false);
        etActivityCost.setEnabled(false);
        etIncreaseCost.setEnabled(false);
        etDevelopCost.setEnabled(false);
        etCmments.setEnabled(false);
      }
    } else {
      if ("T".equals(ifRealDateCode)) {
        tvIfReal.setText(ifRealDateName);
      } else if ("F".equals(ifRealDateCode)) {
        tvIfReal.setText(ifRealDateName);
      }
      tvDataStatus.setText(R.string.draft);
      tvStaffName.setText(mUser.getRealName());
      tvSalesman.setText(mUser.getRealName());
      tvRegisterTime.setText(MyDateUtil.dateToString(new Date(), MyDateUtil.TYPE_DATE));
    }
  }

  public TextWatcher textWatcher() {
    return new TextWatcher() {
      @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {

      }

      @Override public void onTextChanged(CharSequence s, int start, int before, int count) {
        try {
          int planNum = 0;
          int realNum = 0;
          /** 业务增长费比=业务增长费/实销金额（是否实销为“是”）  或   进货金额（是否实销为“否”）  */
          double increaseCost = 0;
          double planMoney = 0;
          double realMoney = 0;
          double monthDiff = 0.0;//增长比

          if (!TextUtils.isEmpty(etEstimateSales.getText().toString())) {
            planNum = Integer.parseInt(etEstimateSales.getText().toString());
          }
          if (!TextUtils.isEmpty(etActualSales.getText().toString())) {
            realNum = Integer.parseInt(etActualSales.getText().toString());
          }
          if (!TextUtils.isEmpty(etIncreaseCost.getText().toString())) {
            increaseCost = Double.parseDouble(etIncreaseCost.getText().toString());
          }
          if (!TextUtils.isEmpty(etPlanMoney.getText().toString())) {
            planMoney = Double.parseDouble(etPlanMoney.getText().toString());
          }
          if (!TextUtils.isEmpty(etRealMoney.getText().toString())) {
            realMoney = Double.parseDouble(etRealMoney.getText().toString());
          }
          String diffrentNum = String.valueOf(planNum - realNum);
          tvMargin.setText(diffrentNum);//库存数

          if ("T".equals(ifRealDateCode)) {
            if (!TextUtils.isEmpty(etIncreaseCost.getText().toString()) && !TextUtils.isEmpty(
                etRealMoney.getText().toString())) {
              monthDiff = increaseCost / realMoney * 100;
            }
          } else if ("F".equals(ifRealDateCode)) {
            if (!TextUtils.isEmpty(etIncreaseCost.getText().toString()) && !TextUtils.isEmpty(
                etPlanMoney.getText().toString())) {
              monthDiff = increaseCost / planMoney * 100;
            }
          }
          DecimalFormat decimalFormat = new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
          monthDiffString = decimalFormat.format(monthDiff);
          tvMonthDiff.setText(monthDiffString + "%");
        } catch (NumberFormatException e) {
          e.printStackTrace();
        }
      }

      @Override public void afterTextChanged(Editable s) {

      }
    };
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    switch (mMenuType) {

      case ADD:
        inflater.inflate(R.menu.menu_save_submit, menu);
        menu.getItem(1).setTitle(R.string.saveAndSubmit);
        break;
      case EDIT:
        inflater.inflate(R.menu.menu_save_submit_delete, menu);
        menu.getItem(0).setTitle(R.string.save);
        menu.getItem(1).setTitle(R.string.submit);
        break;
      case WAIT_CHECK:
        inflater.inflate(R.menu.menu_stop, menu);
        menu.getItem(0).setTitle(R.string.reback_edit);
        break;
      default:
        break;
    }
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
      case android.R.id.home:
        getActivity().finish();
        break;
      //保存
      case R.id.menu_item_save:
        //                if (Double.parseDouble(monthDiffString)>999999.99){
        //                        ToastUtil.show("业务增长费比不能超过 999999.99%");
        //                }else

        if (TextUtils.isEmpty(tvMonth.getText().toString())
          //                        || TextUtils.isEmpty(etUnitPrice.getText().toString())
          //                        || TextUtils.isEmpty(etActualSales.getText().toString())
            ) {
          ToastUtil.show(R.string.notComplete);
        } else {
          volleyPostSave(SAVE);
        }
        break;
      //提交
      case R.id.menu_item_submit:
        //详情界面提交
        if (content != null) {
          if (!content.getRegStaffName().equals(mUser.getRealName())) {
            ToastUtil.show(R.string.regName_submit);
          } else {
            if (content.getDataStatus().equals("草稿") || content.getDataStatus().equals("退回修改")) {
              volleyPostSubmit();
            } else {
              ToastUtil.show(R.string.newOrback);
            }
          }
        }
        //添加界面  保存并提交  菜单
        else {
          if (TextUtils.isEmpty(tvMonth.getText().toString())) {
            ToastUtil.show(R.string.notComplete);
          } else {
            showDialog(SAVE_SUBMIT);
          }
        }

        break;
      //退回
      case R.id.menu_item_stop:
        if (!content.getRegStaffName().equals(mUser.getRealName())) {
          ToastUtil.show(R.string.onlyCreaterBack);
        } else {
          if (content.getDataStatus().equals("已提交")) {
            volleyPostStop();
          } else {
            ToastUtil.show(R.string.onlyNewOrBackEdit);
          }
        }

        break;
      //删除
      case R.id.menu_item_delete:
        if (!content.getRegStaffName().equals(mUser.getRealName())) {
          ToastUtil.show(R.string.onlyRegisterDelete);
        } else {
          if (content.getDataStatus().equals("草稿") || content.getDataStatus().equals("退回修改")) {
            //                        volleyPostDelete();
            BaseConfirmDialogFragment dialog =
                BaseConfirmDialogFragment.newInstance(R.string.deleteConfirm);
            FragmentManager fm = getActivity().getSupportFragmentManager();
            dialog.setTargetFragment(ProductDevelopDetailFragment.this, DELETE);
            dialog.show(fm, "");
          } else {
            ToastUtil.show(R.string.onlyNewOrBackDelete);
          }
        }

        break;

      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  private void showDialog(int requestCode) {
    DialogFragment dialog =
        BaseConfirmDialogFragment.newInstance(R.string.cannotEdit, R.string.hintMessage);
    FragmentManager fm = getActivity().getSupportFragmentManager();
    dialog.setTargetFragment(this, requestCode);
    dialog.show(fm, "");
  }

  /*保存*/
  private void volleyPostSave(int requestCode) {
    String url = ApiConst.getAbsoluteUrl(ApiConst.ULR_PRODUCTDEVELOP_SAVE);

    HashMap<String, String> params = new HashMap<>();
        /*添加保存时不传id*/
    //        if (mMenuType == EDIT) {
    //            params.put("id", content.getId());
    //        }
    params.put("id", id);
    params.put("inMonth", tvMonth.getText().toString());
    params.put("marketend", etMarketName.getText().toString());//终端市场名称  (特殊  有)
    params.put("customer", tvCustomer.getText().toString());//客户
    params.put("productKind", tvProductType.getText().toString());//产品类型
    params.put("product", tvProductName.getText().toString());//产品名称

    params.put("receiptPrice", etUnitPrice.getText().toString());//单价
    params.put("planMoney", etPlanMoney.getText().toString());//进货金额
    params.put("ifRealData", ifRealDateCode);//是否实销
    params.put("planData", etEstimateSales.getText().toString());//进货数量
    params.put("realData", etActualSales.getText().toString());//实销数量
    params.put("realMoney", etRealMoney.getText().toString());//实销金额
    params.put("different", tvMargin.getText().toString());//库存数
    params.put("activityCost", etActivityCost.getText().toString());//业务活动费
    params.put("increaseCost", etIncreaseCost.getText().toString());//业务增长费
    params.put("developCost", etDevelopCost.getText().toString());//开发费
    params.put("monthDiff", tvMonthDiff.getText().toString());//业务增长费比
    params.put("comments", etCmments.getText().toString());//备注

    params.put("dataStatus", dataStatus);//数据状态
    params.put("salesManName", saleManName);//业务员name
    params.put("salesManId", saleManId);//业务员id
    params.put("memberCode", mUser.getMemberCode());
    params.put("Remark", "");
    params.put("customerId", customerId == null ? "" : customerId);//客户名称Id（新增）
    params.put("productKindId", mProductKindId == null ? "" : mProductKindId);//产品类型Id（新增）
    params.put("productId", productId == null ? "" : productId);//产品名称Id（新增）
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, response(requestCode));
  }

  private VolleyResponse response(final int requestCode) {
    return new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        try {
          LogUtil.i("response=" + arg0);
          MyUtils.dismissDialog();
          SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == success || null == success.getResult()) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          String successType = success.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {
            if (SAVE == requestCode) {
              Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();
              getActivity().setResult(Activity.RESULT_OK);
              getActivity().finish();
            } else if (SAVE_SUBMIT == requestCode) {
              volleyPostSubmit();
            }
          }
        } catch (JsonSyntaxException e) {
          e.printStackTrace();
        }
      }
    };
  }

  /*提交*/
  private void volleyPostSubmit() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.ULR_PRODUCTDEVELOP_SUBMIT);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", id);
    params.put("newDataStatus", "submit");
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, response());
  }

  /*退回*/
  private void volleyPostStop() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.ULR_PRODUCTDEVELOP_BACK);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", id);
    params.put("newDataStatus", "newback");
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, response());
  }

  /*删除*/
  private void volleyPostDelete() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.ULR_PRODUCTDEVELOP_DELETE);
    HashMap<String, String> params = new HashMap<>();
    params.put("ids", id);
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, response());
  }

  private VolleyResponse response() {
    return new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        try {
          LogUtil.i("response=" + arg0);
          MyUtils.dismissDialog();
          SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == success || null == success.getResult()) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          String successType = success.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {
            Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();

            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          }
        } catch (JsonSyntaxException e) {
          e.printStackTrace();
        }
      }
    };
  }

  @Override public void onClick(View v) {
    switch (v.getId()) {
      case R.id.ib_month:
        DialogFragment dialog = new BaseMonthTimeDialogFragment();
        FragmentManager fm = getActivity().getSupportFragmentManager();
        dialog.setTargetFragment(this, DATE);
        dialog.show(fm, "");
        break;
      case R.id.ib_realTime:
        DialogFragment realDialog = new BaseYMDTimeDialogFragment();
        FragmentManager fm1 = getActivity().getSupportFragmentManager();
        realDialog.setTargetFragment(this, REALDTAE);
        realDialog.show(fm1, "");
        break;
      case R.id.ib_customer:
        //跳转到客户名录列表界面,单选
        Intent customer = new Intent(getActivity(), CustomerListChooseActivity.class);
        startActivityForResult(customer, CUSTOMER);
        break;
      case R.id.ib_productType:
        //产品台账列表,单选
        Intent product = new Intent(getActivity(), ChooseProductListActivity.class);
        startActivityForResult(product, PRODUCT);
        break;
      case R.id.ib_ifReal:
        //是否实销 IFREAL
        DialogFragment ifrealDialog = new IsOrNotDialogFragment();
        FragmentManager fm2 = getActivity().getSupportFragmentManager();
        ifrealDialog.setTargetFragment(this, IFREAL);
        ifrealDialog.show(fm2, "");

        break;
      case R.id.ib_salesMan:
        //业务员
        Intent i = new Intent(getActivity(), AppointerListActivity.class);
        startActivityForResult(i, SALES_MAN);
        break;
      default:
        break;
    }
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }

    //时间
    if (requestCode == DATE) {

      Date mdate = (Date) data.getSerializableExtra(BaseMonthTimeDialogFragment.EXTRA_DATE);
      String date = MyDateUtil.dateToString(mdate, MyDateUtil.TYPE_DATE4);
      LogUtil.i("添加时间===" + date);
      tvMonth.setText(date);
      //查询进货数量
      if (!TextUtils.isEmpty(tvMonth.getText().toString())
          && !TextUtils.isEmpty(customerName)
          && !TextUtils.isEmpty(productName)) {
        volleyPostNum();
      }
    }
    //        //实销时间
    //        if (requestCode == REALDTAE) {
    //
    //            Date mdate = (Date) data.getSerializableExtra(BaseYMDTimeDialogFragment.EXTRA_DATE);
    //            realDate = MyDateUtil.dateToString(mdate, MyDateUtil.TYPE_DATE);
    //            LogUtil.i("添加时间===" + realDate);
    //            tvRealTime.setText(realDate);
    //        }

    //客户
    if (requestCode == CUSTOMER) {
      customerName = data.getStringExtra("customerName");
      customerId = data.getStringExtra("customerId");
      tvCustomer.setText(customerName);
      etUnitPrice.setText("");
      //查询进货数量
      if (!TextUtils.isEmpty(tvMonth.getText().toString())
          && !TextUtils.isEmpty(customerName)
          && !TextUtils.isEmpty(productName)) {
        volleyPostNum();
      }
      //查询产品单价
      if (!TextUtils.isEmpty(customerName) && !TextUtils.isEmpty(productName)) {
        volleyPostPrice();
      }
    }

    //产品
    if (requestCode == PRODUCT) {
      ProductLedgerOriginal.ProductLedgerContent mContent =
          (ProductLedgerOriginal.ProductLedgerContent) data.getSerializableExtra(
              ChooseProductListFragment.EXTRA_CONTENT);
      productName = mContent.getProductName();//产品名
      productId = mContent.getId();
      String productType = mContent.getMaterialKindCom();
      mProductKindId = mContent.getMaterialKindCode();//产品类别iid .
      tvProductName.setText(productName);
      tvProductType.setText(productType);
      etUnitPrice.setText("");
      //查询进货数量
      if (!TextUtils.isEmpty(tvMonth.getText().toString())
          && !TextUtils.isEmpty(customerName)
          && !TextUtils.isEmpty(productName)) {
        volleyPostNum();
      }
      //查询产品单价
      if (!TextUtils.isEmpty(customerName) && !TextUtils.isEmpty(productName)) {
        volleyPostPrice();
      }
    }
    if (requestCode == DELETE) {
      volleyPostDelete();
    }
    if (requestCode == IFREAL) {
      CustomerDialog content =
          (CustomerDialog) data.getSerializableExtra(IsOrNotDialogFragment.EXTRA_VALUE);
      ifRealDateName = content.getName();
      ifRealDateCode = content.getId();
      tvIfReal.setText(ifRealDateName);
    }
    //业务员
    if (requestCode == SALES_MAN) {
      CustomerDialog saleMan =
          (CustomerDialog) data.getSerializableExtra(AppointerListFragment.EXTRA_VALUE);
      saleManName = saleMan.getName();
      saleManId = saleMan.getId();
      tvSalesman.setText(saleManName);
    }
    if (requestCode == SAVE_SUBMIT) {
      volleyPostSave(SAVE_SUBMIT);
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  private void volleyPostPrice() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_PRICE_LIST);
    HashMap<String, String> params = new HashMap<>();

    params.put("memberCode", mUser.getMemberCode());
    params.put("productId", productId);
    params.put("customerId", customerId);
    params.put("productName", productName);
    params.put("customerName", customerName);
    params.put("dataStatus", "publish");
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        ProductLedgerOriginal original = new Gson().fromJson(arg0, ProductLedgerOriginal.class);
        ArrayList<ProductLedgerOriginal.ProductLedgerContent> rows =
            (ArrayList<ProductLedgerOriginal.ProductLedgerContent>) original.getRows();
        if (rows != null && rows.size() != 0) {
          String unitPrice = rows.get(0).getSalePrice();
          etUnitPrice.setText(unitPrice);
          if (!TextUtils.isEmpty(etUnitPrice.getText())) {
            etUnitPrice.setEnabled(false);
          } else {
            etUnitPrice.setEnabled(true);
          }
        } else {
          etUnitPrice.setEnabled(true);
        }
      }
    });
  }

  //获取进货数量
  private void volleyPostNum() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_IN_NUMBER);
    HashMap<String, String> params = new HashMap<>();
    params.put("memberCode", mUser.getMemberCode());
    params.put("inMonth", tvMonth.getText().toString());
    params.put("materialName", productName);
    params.put("mcustomerName", customerName);
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        NumberOriginal original = new Gson().fromJson(arg0, NumberOriginal.class);
        NumberOriginal.NumberContent num = original.getRows().get(0);
        if (null == original || null == original.getTotal()) {
          Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
          return;
        }
        String successType = original.getTotal();
        if (successType.equals(SuccessMessage.FAILURE)) {
          Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
          return;
        }
        if (successType.equals(SuccessMessage.SUCCESS)) {
          etEstimateSales.setText(num.getMoutNumber());
        }
      }
    });
  }

  public static ProductDevelopDetailFragment newInstence(
      ProductSalesOriginal.ProductSalesContent content) {
    Bundle bundle = new Bundle();
    bundle.putSerializable(EXTRA_CONTENT, content);
    ProductDevelopDetailFragment mfragment = new ProductDevelopDetailFragment();
    mfragment.setArguments(bundle);
    return mfragment;
  }
}
